<template>
  <div class="category-container">
    <div class="page-header">
      <h2>类型管理</h2>
      <el-button type="primary" @click="handleCreate" :icon="Plus"
        >新建类型</el-button
      >
    </div>

    <el-card>
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="类型名称" width="250" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="style" label="卡片模板" width="120">
          <template #default="{ row }">
            {{ styleMap[row.style] || row.style }}
          </template>
        </el-table-column>
        <el-table-column prop="questionNum" label="题目数" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="类型名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="parentId">
          <el-select
            v-model="form.parentId"
            placeholder="不选则为一级分类"
            clearable
            :disabled="isEditingTopLevel"
          >
            <el-option
              v-for="cat in l1Categories"
              :key="cat.id"
              :label="cat.name"
              :value="cat.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            :max="999"
            placeholder="请输入排序值"
          />
        </el-form-item>
        <el-form-item label="卡片模板" prop="style">
          <el-select v-model="form.style" placeholder="请选择卡片模板">
            <el-option
              v-for="option in styleOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入类型描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  pageQueryCategoryList,
  addCategory,
  updateCategory,
  deleteCategory,
} from "@/api/category";
import { ElMessage, ElMessageBox } from "element-plus";

const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();

const tableData = ref([]);
const allCategories = ref([]);

const l1Categories = computed(() =>
  allCategories.value.filter((c) => c.parentId === 0)
);

// 判断是否为编辑一级分类
const isEditingTopLevel = computed(() => {
  return form.categoryId && form.parentId === 0
})


// 卡片模板选项数组
const styleOptions = [
  { label: "黄色", value: "yellow" },
  { label: "蓝色", value: "blue" },
  { label: "绿色", value: "green" },
  { label: "红色", value: "red" },
  { label: "紫色", value: "purple" },
  { label: "浅绿色", value: "light-green" },
];

// 将 style 取值映射为对应的中文标签
const styleMap = Object.fromEntries(
  styleOptions.map((option) => [option.value, option.label])
);

const form = reactive({
  categoryId: null,
  categoryName: "",
  description: "",
  parentId: null,
  sort: 1,
  style: "yellow",
});

const formRules = {
  categoryName: [
    { required: true, message: "请输入类型名称", trigger: "blur" },
  ],
  style: [{ required: true, message: "请选择模板", trigger: "change" }],
};

// 获取列表数据
const fetchList = async () => {
  loading.value = true;
  try {
    // 获取所有数据用于构建树，因此设置一个较大的pageSize
    const data = await pageQueryCategoryList({ pageNum: 1, pageSize: 999 });
    allCategories.value = data.list || [];
    tableData.value = buildTree(allCategories.value, 0); // 假设一级分类的 parentId 是 0
  } catch (error) {
    console.error("获取类型列表失败:", error);
    ElMessage.error("获取类型列表失败");
  } finally {
    loading.value = false;
  }
};

const buildTree = (items, parentId = 0) => {
  return items
    .filter((item) => item.parentId === parentId)
    .map((item) => {
      const children = buildTree(items, item.id);
      if (children.length > 0) {
        return { ...item, children, hasChildren: true };
      }
      return item;
    });
};

onMounted(() => {
  fetchList();
});

const handleCreate = () => {
  resetForm();
  dialogTitle.value = "新建类型";
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  resetForm();
  dialogTitle.value = "编辑类型";
  // 过滤掉自身和其子孙，防止循环引用
  l1Categories.value = allCategories.value.filter(
    (c) => c.parentId === 0 && c.id !== row.id
  );
  // 映射后端字段到表单字段
  form.categoryId = row.id;
  form.categoryName = row.name;
  form.description = row.description;
  form.parentId = row.parentId;
  form.sort = row.sort
  form.style = row.style;
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitLoading.value = true;

    if (form.categoryId) {
      await updateCategory(form);
      ElMessage.success("更新成功");
    } else {
      await addCategory(form);
      ElMessage.success("创建成功");
    }

    dialogVisible.value = false;
    fetchList();
  } catch (error) {
    console.error("操作失败:", error);
  } finally {
    submitLoading.value = false;
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除类型 "${row.name}" 吗? 这可能会删除所有子分类。`,
    "警告",
    { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
  )
    .then(async () => {
      try {
        await deleteCategory({ categoryId: row.id });
        ElMessage.success("删除成功");
        fetchList();
      } catch (error) {
        console.error("删除失败:", error);
      }
    })
    .catch(() => {
      // 用户取消
    });
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(form, {
    categoryId: null,
    categoryName: "",
    description: "",
    parentId: null,
    sort: 1,
    style: "yellow",
  });
  l1Categories.value = allCategories.value.filter((c) => c.parentId === 0);
};
</script>

<style scoped>
.category-container {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
  color: #333;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
